/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.commons.web.export.xls;

import static ar.com.greensoft.commons.web.jsf.utils.XlsUtil.*;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import ar.com.greensoft.commons.web.export.ColumnValueMapper;
import ar.com.greensoft.commons.web.export.ExportColInfo;
import ar.com.greensoft.commons.web.export.ResultExporter;
import ar.com.greensoft.commons.web.jsf.utils.FacesUtil;
import ar.com.greensoft.commons.web.jsf.utils.HttpJSFUtil;
import ar.com.greensoft.commons.web.jsf.utils.ResourceBundleUtil;

/**
 * @author Jorge E. Villaverde
 * @version 0.0.1
 * @since 0.0.1
 */
public class ExcelResultExporter<T> implements ResultExporter<T> {
	protected static final Logger logger = Logger.getLogger(ExcelResultExporter.class.getName());

	@Override
	public void exportResult(List<ExportColInfo> colInfoList,
			ColumnValueMapper<T> mapper, List<T> resultList,
			String resultFileName) {
		if (colInfoList == null)
			throw new IllegalArgumentException("colInfoList cannot be null");
		if (mapper == null)
			throw new IllegalArgumentException("ColumnMapper cannot be null");

		FacesContext faces = FacesContext.getCurrentInstance();
		Locale locale = faces.getViewRoot().getLocale();

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet();

		HSSFRow row;

		int rowNumber = 0;

		row = sheet.createRow(rowNumber++);

		HSSFCellStyle headerStyle = createHeaderStyle(wb);
		HSSFCellStyle cellStyle = createCellStyle(wb);

		for (ExportColInfo colInfo : colInfoList) {
			int columnNumber = colInfo.getColumnNumber();
			addCell(
					row,
					columnNumber,
					ResourceBundleUtil.getResourceBundleString(
							colInfo.getColumnName(), locale)).setCellStyle(
					headerStyle);
			sheet.setColumnWidth(columnNumber, colInfo.getColumnWidth());
		}

		if(resultList != null && !resultList.isEmpty()){
			int i = 1;
		
			for (T value : resultList) {
				row = sheet.createRow((short) i);
	
				for (ExportColInfo colInfo : colInfoList) {
					int columnNumber = colInfo.getColumnNumber();
					String cellValue = mapper.getColumnValue(columnNumber, value);
					addCell(row, columnNumber, cellValue).setCellStyle(cellStyle);
				}
				i++;
			}
		}

		HttpServletResponse res = HttpJSFUtil.getResponse();
		res.setContentType(FacesUtil.MS_EXCEL_MIME_TYPE);
		res.setHeader("Content-disposition", "attachment; filename="
				+ resultFileName);

		try {
			ServletOutputStream out = res.getOutputStream();

			wb.write(out);
			out.flush();
			out.close();
		} catch (IOException ex) {
			logger.severe("Error: " + ex.getLocalizedMessage());
		}

		faces.responseComplete();
	}
}
